package com.linkoog.devtools.utils.formatter;

import com.linkoog.devtools.utils.StringUtils;

import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;

public class XMLFormatter {

    public static String pretty(String src){
        return handler(src, true);
    }

    public static String compress(String src){
        return handler(src, false);
    }

    private static String handler(String src, boolean pretty){
        if (StringUtils.isBlank(src)) return src;

        try {
            // 创建TransformerFactory
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            // 设置输出格式
            transformer.setOutputProperty(OutputKeys.INDENT, pretty ? "yes":"no");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

            // 将XML字符串转换为DOMSource
            DOMSource source = new DOMSource(javax.xml.parsers.DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder()
                    .parse(new org.xml.sax.InputSource(new java.io.StringReader(src))));

            // 创建StringWriter来接收格式化的XML
            StringWriter writer = new StringWriter();

            // 将格式化的XML写入StringWriter
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);

            // 获取格式化的XML字符串
            return writer.toString();
        } catch (Exception e) {
        }
        return src;
    }
}


